#coding=utf-8
#LightCam 统一开户 
#init by hfh 20151030

import multiprocessing,subprocess,sys
import socket,os,time,re,traceback,json,binascii
import lc_libs,pymongo

def gen_logfile():
	try:
		
		loglist=[]
		logtime=""
		today=time.strftime('%Y%m%d',time.localtime())
		filename="/cffex/trade/openaccountfront/log/UNICLIENT_%s.log" % today
		comd="tail -1000 %s" % filename
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			lines=line.split(',')
			if len(lines)<7:
				continue
			datestr=lines[0]
			timestr=lines[1]
			try:
				datastr=lines[6].decode('gbk').encode('utf8')
			except:
				pass
			logtime="%s %s" % (datestr,timestr)
			info={
				'logtime':logtime,
				'ipaddr':lines[2],
				'codestr':lines[3],
				'linestr':lines[4],
				'servity':lines[5],
				'datastr':datastr
			}
			loglist.append(info)
		file=open("/monitor/LightCam/temp/loglist.json",'w')
		file.write(json.dumps(loglist))
		file.close()
		
		loglistapi=[]
		tomon=time.strftime('%Y%m',time.localtime())
		filename="/cffex/trade/openaccountfront/recv/clientapi_%s.log" % tomon
		comd="tail -1000 %s" % filename
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			try:
				line=line.strip('\n\r\t ').decode('gbk').encode('utf8')
			except:
				pass
			info={'value':line}
			loglistapi.append(info)
		file=open("/monitor/LightCam/temp/loglistapi.json",'w')
		file.write(json.dumps(loglistapi))
		file.close()
		
		PortState="正常"
		comd="netstat -an|grep ESTABLISHED|awk '{print $5}'|grep -w 51002|wc -l"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		res=popen.stdout.read().strip('\n\r\t ')
		if res != '1':
			PortState="未建立"
		
		UniNumSuccess=""
		UniNumFailed=""
		filename="/monitor/bin/app/unifront.csv"
		for line in open(filename,'rb').readlines():
			lines=line.split(',')
			if len(lines)<8:
				continue
			if lines[1]=='UniNumSuccess':
				UniNumSuccess=lines[6]
			if lines[1]=='UniNumFailed':
				UniNumFailed=lines[6]
		logstate=[
			{'name':'日志更新时间','value':logtime},
			{'name':'保证金监控中心连接状态','value':PortState},
			{'name':'成功请求数量','value':UniNumSuccess},
			{'name':'未通过请求数量','value':UniNumFailed}
			]
		file=open("/monitor/LightCam/temp/logstate.json",'w')
		file.write(json.dumps(logstate))
		file.close()
		
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

def gen_processstatus():
	processstatus=[]
	try:
		comd=r'''
			ps -fu trade|awk 'NR>1{for(i=8;i<=NF;++i) printf $i " ";printf "\n"}'
		'''
		#comd=r'''
		#	cat /monitor/LightCam/temp/process.txt|awk 'NR>1{$1=$2=$3=$4=$5=$6=$7="";print}'
		#'''
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		for line in popen.stdout.read().split('\n'):
			if len(line)<3:
				continue
			info={
				'hostname':agent_hostname,
				'process':line.strip('\r\n ')
			}
			processstatus.append(info)
		#print processstatus
		file=open("/monitor/LightCam/temp/processstatus.json",'w')
		file.write(json.dumps(processstatus))
		file.close()
	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" :\n"+excinfo+"\n")
		logfile.flush()

if __name__ == "__main__":
	
	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	agent_hostname=lc_libs.lc_gethostname()
	
	#初始化数据库
	db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

	db.connect()
	Conn=db.getConn()
	if Conn==None:
		print "Can not Connect to the MondbDB"
		exit(0)
	
	dbname='lc_uniclient'
	psisdb=db.useDatabase(dbname)

	while True:
		time.sleep(0.1)
		try:
			
			#生成日志相关内容
			if agent_hostname in ('unifront1'):
				gen_logfile()
				
			#进程状态统计
			gen_processstatus()
				
			time.sleep(10)

		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" \n"+excinfo+"\n")
			logfile.flush()
			time.sleep(10)
